package com.cms.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
 
import com.cms.common.FileUtil;
import com.google.gson.Gson;

@Controller
public class UploadControrller extends BaseController{

	 @Value("${platform.url:''}")
	 private String url ;
	
	 /***
	  * 
	  * @param request
	  * @param resp
	  * @throws Exception
	  */
	 @RequestMapping(value="/uploadifyServlet.do",method=RequestMethod.POST)
	 public void uploadFile(HttpServletResponse response,HttpServletRequest request,@RequestParam(value="file", required=false) MultipartFile file) 
	 throws IOException{  
	        byte[] bytes = file.getBytes();  
	        System.out.println(file.getOriginalFilename());  
	        String uploadDir = request.getRealPath("/")+"upload";  
	        File dirPath = new File(uploadDir);  
	        if (!dirPath.exists()) {  
	            dirPath.mkdirs();  
	        }  
	        File uploadedFile = new File(uploadDir + File.separator  + FileUtil.generateFile(file.getOriginalFilename()));  
	        FileCopyUtils.copy(bytes, uploadedFile);  
	        String msg = "true";  
	        Map<String,Object>result = new HashMap<String, Object>();
	        result.put("file", uploadedFile.getName());
	        result.put("msg", msg);
	        result.put("orgFile", file.getOriginalFilename());
	        this.renderText(response, new Gson().toJson(result));
	    }  
	 
	 
	 @RequestMapping(value="/kindeditorServlet.do")
	 public void uploadKindeditor(HttpServletResponse response,HttpServletRequest request) throws IOException, FileUploadException
	 {
		 Map<String, Object>obj= new HashMap<String, Object>();
		 FileItemFactory factory = new DiskFileItemFactory();
		 ServletFileUpload upload = new ServletFileUpload(factory);
		 upload.setHeaderEncoding("UTF-8");
		 List<FileItem> items = upload.parseRequest(request);
		 if(items!=null&&!items.isEmpty())
		 {
		 String savePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
		 Iterator<FileItem> itr = items.iterator();
		 while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				String fileName = item.getName();
				if (!item.isFormField()) {
					//检查扩展名
					String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
					String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
					try{
						File uploadedFile = new File(savePath, newFileName);
						item.write(uploadedFile);
					}catch(Exception e){
						return;
					}
					obj.put("error", 0);
					obj.put("url", url+"/upload/" + newFileName);
					obj.put("uploadUrl", newFileName);
				}
			}
		 }
		 else
		 {
			    obj.put("error",1);
				obj.put("message", "请选择需要上传的文件。");
		 }
		 this.renderText(response, new Gson().toJson(obj));
	 }  
	 
	 
	 @RequestMapping(value="/uploadFile.do")
	 public void uploadFile(HttpServletResponse response,HttpServletRequest request) throws IOException, FileUploadException
	 {
		 Map<String, Object>obj= new HashMap<String, Object>();
		 FileItemFactory factory = new DiskFileItemFactory();
		 ServletFileUpload upload = new ServletFileUpload(factory);
		 upload.setHeaderEncoding("UTF-8");
		 List<FileItem> items = upload.parseRequest(request);
		 if(items!=null&&!items.isEmpty())
		 {
		 String savePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
		 Iterator<FileItem> itr = items.iterator();
		 while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				String fileName = item.getName();
				if (!item.isFormField()) {
					//检查扩展名
					String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
					String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
					try{
						File uploadedFile = new File(savePath, newFileName);
						item.write(uploadedFile);
					}catch(Exception e){
						return;
					}
					obj.put("error", 0);
					obj.put("url", newFileName);
				    obj.put("orgFile", fileName);
				}
			}
		 }
		 else
		 {
			    obj.put("error",1);
				obj.put("message", "请选择需要上传的文件。");
		 }
		 this.renderText(response, new Gson().toJson(obj));
	 }  
}
